package bog

import org.springframework.dao.DataIntegrityViolationException
import org.springframework.validation.Errors

class UserController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index() {
        redirect(action: "list", params: params)
    }

    def list(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        [userInstanceList: User.list(params), userInstanceTotal: User.count()]
    }

    def create() {
        [userInstance: new User(params)]
    }

    def save() {
        params.password = ((String)params.password).encodeAsMD5()

        def userInstance = new User(params)
        if (!userInstance.save(flush: true)) {
            if (userInstance.hasErrors()) {

                def usernameError
                if (userInstance.errors.hasFieldErrors("username"))
                    usernameError = true

                def birthDateError
                if (userInstance.errors.hasFieldErrors("birthDate"))
                     birthDateError = true

                def passwordError
                if (userInstance.errors.hasFieldErrors("password"))
                    passwordError = true
                userInstance.clearErrors();

                def errors = userInstance.getErrors()
                if (usernameError)
                    errors.putAt("username", "Username is already selected or it must contains 5 to 12 charachter")

                if (birthDateError)
                    errors.putAt("birthDate", "You must be over 18!")

                if (passwordError)
                    errors.putAt("password", "Your password should contains 6 to 12 character and should be diffrent form username")
            }
            render(view: "create", model: [userInstance: userInstance])
            return
        }


        flash.message = message(code: 'default.created.message', args: [message(code: 'user.label', default: 'User'), userInstance.id])
        userInstance.save()
        redirect(action: "show", id: userInstance.id)
    }

    def login = {
         if (params.cName) {
             return [cName:params.cName, aName:params.aName]
         }
    }

    def doLogin = {
        def user = User.findWhere(username: params['username'],
                                    password: params['password'].encodeAsMD5())

        session.user = user;

        if (user) {
            if (params.cName) {
                redirect(controller: params.cName, action: params.aName)
            } else {
                redirect(controller: "index", action: "index")
            }

        } else {
            flash.message = "Invalid username and password"
            redirect(controller: "user", action: "login")
        }

    }

    def logout() {
        session.user = null
        redirect(controller: "index", action: "index")

    }

    def show(Long id) {
        def userInstance = User.get(id)
        if (!userInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), id])
            redirect(action: "list")
            return
        }

        // int reputation = 10
       // reputation = userInstance.getReputation()

        log.info("user reputation: " + userInstance.getReputation())
        [userInstance: userInstance, userReputation: userInstance.getReputation()]
    }

    def edit(Long id) {
        def userInstance = User.get(id)
        if (!userInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), id])
            redirect(action: "list")
            return
        }

        [userInstance: userInstance]
    }

    def update(Long id, Long version) {
        def userInstance = User.get(id)
        if (!userInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), id])
            redirect(action: "list")
            return
        }

        if (version != null) {
            if (userInstance.version > version) {
                userInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                        [message(code: 'user.label', default: 'User')] as Object[],
                        "Another user has updated this User while you were editing")
                render(view: "edit", model: [userInstance: userInstance])
                return
            }
        }

        userInstance.properties = params

        if (!userInstance.save(flush: true)) {
            render(view: "edit", model: [userInstance: userInstance])
            return
        }

        flash.message = message(code: 'default.updated.message', args: [message(code: 'user.label', default: 'User'), userInstance.id])
        redirect(action: "show", id: userInstance.id)
    }

    def delete(Long id) {
        def userInstance = User.get(id)
        if (!userInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), id])
            redirect(action: "list")
            return
        }

        try {
            userInstance.delete(flush: true)
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'user.label', default: 'User'), id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'user.label', default: 'User'), id])
            redirect(action: "show", id: id)
        }
    }


}
